package com.baizhi.config;

import com.baizhi.realm.MyPermissionRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfigAuthentication {
    /**
     * 1. filter 过滤器
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
//        过滤链  书写过滤规则 哪些要拦截  哪些不拦截
        Map map = new HashMap();
////        设置过滤规则
//        anon  匿名可访问  不用登录就可以访问
//        authc 认证后可访问  登录后可以访问
        map.put("/login.jsp", "anon");
        map.put("/admin/login","anon");
        map.put("/**", "anon");
        filterFactoryBean.setFilterChainDefinitionMap(map);
//        设置安全管理器
        filterFactoryBean.setSecurityManager(securityManager);

        filterFactoryBean.setUnauthorizedUrl("/login.jsp");
        return filterFactoryBean;
    }

    /**
     * 2. SecurityManager
     */
    @Bean
    public SecurityManager getSecurityManager(MyPermissionRealm dataSourceRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(dataSourceRealm);
        return securityManager;
    }


    /**
     *  开启shiro aop注解支持.
     *  使用代理方式;所以需要开启代码支持;否则@RequiresRoles等注解无法生效
     * @param securityManager
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
